<?php


namespace models\Business;


use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use models\Exception\Business\CodeException;
use models\Exception\Business\MemberException;
use Yaf\Registry;
use youliPhpLib\Common\Encrypt;
use youliPhpLib\Common\StringOperation;

class PicCode
{
    const ALLOWED_ACTION = 'login,register';

    /**
     * @param string $mobile
     * @param string $action
     * @param string $verification
     * @param bool $is_captcha
     * @return string
     * @throws CodeException
     * @throws MemberException
     */
    static public function genPicCode($mobile = '', $action = 'register', $verification = '', $is_captcha = false) {
        try {
            $mobile = !empty($mobile) && is_string($mobile) ? trim($mobile) : '';
            $action = !empty($action) && strpos(self::ALLOWED_ACTION, $action) !== false ?
                trim($action)  : '';

            if (empty($mobile))
                throw new MemberException(MemberException::MEMBER_MOBILE_EMPTY, MemberException::MEMBER_MOBILE_EMPTY_NO);

            if (empty($action))
                throw new CodeException(CodeException::INVALID_TYPE, CodeException::INVALID_TYPE_NO);

            $cache_name = Encrypt::encrypt(
                urldecode(http_build_query(['mobile' => $mobile, 'action' => $action, 'is_captcha' => $is_captcha]))
            );

            $redis = Registry::get('redis');
            $redis->auth(Registry::get('config')['redis']['master']['auth']);
            $redis->select(3);
            $redis->pipeline();
            $verification_str = $redis->get($cache_name);
            if ($verification_str)
                Registry::get('redis_string')->deleteString($cache_name);
            // 创建图形验证码
            $phrase = StringOperation::getRandStr('letter', 4);
            Registry::get("redis")->setex($cache_name, Registry::get("config")["sms"]["expire"], json_encode(['verification' => $phrase]));
            $redis->setnx($cache_name, $phrase);
            $redis->exec();

            // 我电脑上没有freetype模块，并且有点懵逼不知道该怎么安装，所以这段代码注释掉
            $captcha_name = $cache_name . ".jpg";
            /*$builder = new CaptchaBuilder($phrase);
            $builder->build();
            $builder->save($captcha_name);*/

            return Registry::get('config')['application']['host'] . $captcha_name;
        } catch (MemberException $e) {
            throw $e;
        } catch (CodeException $e) {
            throw $e;
        } catch (\Exception $e) {
            throw $e;
        }
    }
}
